package com.wechat.controller;

import com.wechat.apidoc.WxQuestionInterface;
import com.wechat.entity.Question;
import com.wechat.entity.QuestionDetail;
import com.wechat.entity.QuestionLib;
import com.wechat.entity.User;
import com.wechat.service.PayService;
import com.wechat.service.QuestionService;
import com.wechat.service.UserService;
import com.wechat.utils.ActionResult;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;


/**
 *
 * @author ycx
 * @date 2018/4/11
 */
@RestController
@RequestMapping(value = "api/v1")
public class WxQuestionController implements WxQuestionInterface {

    private static Logger logger = LoggerFactory.getLogger(WxQuestionController.class);

    @Value("${redpackage.minamount:1}")
    private int redPackageMinAmount;

    @Autowired
    private QuestionService questionService;
    @Autowired
    private UserService userService;
    @Autowired
    private PayService payService;

    /**
     * 初始化出题记录(开始出题)
     *
     * @param key
     * @return
     */
    @Override
    @RequestMapping(value = "question/save_question", method = RequestMethod.POST)
    public ActionResult saveQuestion(String key) {
        logger.info("[初始化出题记录接口]:{}", "key=" + key);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if (user == null) {
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        try {
            Integer userId = user.getId();
            Question question = new Question();
            question.setUserId(userId);
            questionService.saveQuestion(question);

            result.setData(question.getId());
            result.setMessage("初始化出题记录成功");
            result.setSuccess(true);
        } catch (Exception e) {
            logger.warn("[初始化出题记录接口异常]：", e);

            result.setMessage("初始化出题记录失败");
            result.setSuccess(false);
        }

        return result;
    }

    /**
     * 提交出题任务
     *
     * @param id
     * @param key
     * @return
     */
    @Override
    @RequestMapping(value = "question/commit_question", method = RequestMethod.POST)
    public ActionResult<?> commitQuestion(Integer id, String key) {
        logger.info("[提交出题任务接口]:{}", "key=" + key + ",id=" + id);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if (user == null) {
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (id == null || id == 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            int questionNum = questionService.questionNum(id);

            Question question = questionService.findQuestion(id);
            question.setTotalQuestionNumber((short) questionNum);
            question.setDataState((short) 1);
            question.setUpdateTime(new Date());
            questionService.updateQuestion(question);

            result.setMessage("提交出题任务成功");
            result.setSuccess(true);
        } catch (Exception e) {
            logger.warn("[提交出题任务接口异常]：", e);

            result.setMessage("提交出题任务失败");
            result.setSuccess(false);
        }

        return result;
    }

    /**
     * 设置红包
     *
     * @param id
     * @param totalAmount
     * @param totalNumber
     * @param totalRight
     * @param key
     * @return
     */
    @Override
    @RequestMapping(value = "question/set_red_packet", method = RequestMethod.POST)
    public ActionResult setRedPacket(Integer id, BigDecimal totalAmount, Short totalNumber, Short totalRight, String key, HttpServletRequest request) {
        logger.info("[设置红包接口]:{}", "key=" + key + ",id=" + id + ",totalAmount=" + totalAmount + ",totalNumber=" + totalNumber + ",totalRight=" + totalRight);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if (user == null) {
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }
        boolean bool = (totalAmount == null || (totalAmount.intValue() > 200)) || (totalNumber == null || totalNumber <= 0)
                || (totalRight == null || totalRight <= 0);
        if (bool) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }
        // 直接舍弃第三位小数，万一结果是0.099
        BigDecimal avgMoney = totalAmount.divide(new BigDecimal(totalNumber), 2, BigDecimal.ROUND_DOWN);
        // 为什么要>10，因为本来是0.1的现在两边乘于100化整好算点
        if (avgMoney.multiply(new BigDecimal(100)).intValue() < redPackageMinAmount) {
            result.setMessage("人均红包不能少于0.1元");
            result.setSuccess(false);
            return result;
        }


        try {
            int questionNum = questionService.questionNum(id);
            if(totalRight>questionNum){
                result.setMessage("领红包条件不能超过总题数");
                result.setSuccess(false);
                return result;
            }

            Question question = questionService.findQuestion(id);
            if(question.getAmountStatus() > 0){
                result.setMessage("已经设置过红包");
                result.setSuccess(false);
                return result;
            }

            question.setUpdateTime(new Date());
            question.setTotalAmount(totalAmount);
            question.setTotalNumber(totalNumber);
            question.setTotalRight(totalRight);
            question.setSurplusNumber(totalNumber);

            questionService.updateQuestion(question);

            Map<String, String> resultMap = payService.unifiedOrder(user, totalAmount, id, request);

            result.setData(resultMap);
            result.setMessage("设置红包成功");
            result.setSuccess(true);
        } catch (Exception e) {
            logger.warn("[设置红包接口异常]：", e);

            result.setMessage("设置红包失败");
            result.setSuccess(false);
        }

        return result;
    }

    /**
     * 查询出题记录总记录
     *
     * @param id
     * @param key
     * @return
     */
    @Override
    @RequestMapping(value = "question/sel_question", method = RequestMethod.POST)
    public ActionResult selQuestion(Integer id, String key) {
        logger.info("[查询出题记录总记录接口]:{}", "key=" + key + ",id=" + id);

        ActionResult result = new ActionResult<>();

        User loginUser = userService.getLoginUser(key);
        if (loginUser == null) {
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (id == null || id == 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            Question question = questionService.findQuestion(id);
            User user = userService.findById(loginUser.getId());

            result.put("user", user);
            result.setData(question);
            result.setMessage("查询出题记录总记录成功");
            result.setSuccess(true);
        } catch (Exception e) {
            logger.warn("[查询出题记录总记录接口异常]：", e);

            result.setMessage("查询出题记录总记录失败");
            result.setSuccess(false);
        }

        return result;
    }

    /**
     * 提交出题记录答案
     *
     * @param questionId
     * @param questionLibId
     * @param trueAnswer
     * @param key
     * @return
     */
    @Override
    @RequestMapping(value = "question/save_question_detail", method = RequestMethod.POST)
    public ActionResult saveQuestionDetail(Integer questionId, Integer questionLibId, String trueAnswer, String key) {
        logger.info("[提交出题记录答案接口]:{}", "key=" + key + ",questionId=" + questionId + ",questionLibId=" + questionLibId + ",trueAnswer" + trueAnswer);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if (user == null) {
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        boolean check = (questionId == null || questionId == 0) || (questionLibId == null || questionLibId == 0)
                || StringUtils.isBlank(trueAnswer);
        if (check) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            QuestionDetail questionDetail = new QuestionDetail();
            questionDetail.setUserId(user.getId());
            questionDetail.setQuestionId(questionId);
            questionDetail.setQuestionLibId(questionLibId);
            questionDetail.setTrueAnswer(trueAnswer);
            questionService.saveQuestionDetail(questionDetail);

            int questionNum = questionService.questionNum(questionId);

            result.setMessage("提交出题记录答案保存成功");
            result.setData(questionNum);
            result.setSuccess(true);
        } catch (Exception e) {
            logger.warn("[提交出题记录答案接口异常]：", e);

            result.setMessage("提交出题记录答案保存失败");
            result.setSuccess(false);
        }

        return result;
    }


    /**
     * 随机从题库查询出一条与之前不重复的题目
     *
     * @param questionId
     * @param key
     * @return
     */
    @Override
    @RequestMapping(value = "question/sel_not_repeat_question", method = RequestMethod.POST)
    public ActionResult selNotRepeatQuestion(Integer questionId, String key) {
        logger.info("[随机从题库查询出一条与之前不重复的题目接口]:{}", "key=" + key + ",questionId=" + questionId);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if (user == null) {
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (questionId == null || questionId == 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            QuestionLib questionLib = questionService.findNotRepeatQuestion(questionId);

            result.setMessage("随机从题库查询出一条与之前不重复的题目成功");
            result.setData(questionLib);
            result.setSuccess(true);
        } catch (Exception e) {
            logger.warn("[随机从题库查询出一条与之前不重复的题目接口异常]：", e);

            result.setMessage("随机从题库查询出一条与之前不重复的题目失败");
            result.setSuccess(false);
        }

        return result;
    }

}



















































